<?php
namespace Admin\Controller;
use Admin\Service\User;
class BaseController extends \Think\Controller{

    public $userInfo;
    public $adminUser;
    protected $wiki_dir;

    protected function _initialize() {
        //wiki文档目录
        $this->wiki_dir = C('WIKI_DIR') ? C('WIKI_DIR') : 'wiki';
        C(array(
            'NOT_AUTH_MODULE' => 'Public', //无需认证模块
            'USER_AUTH_GATEWAY' => U('Public/login'), //登录地址
        ));
        //管理用户模型
        $this->adminUser = User::getInstance();
        //获取用户信息
        $this->userInfo = $this->adminUser->getInfo();
        //验证后台登录权限
        if (!$this->checkAuthModule(CONTROLLER_NAME, C('NOT_AUTH_MODULE'))) {
            if(!$this->checkAdminAccess()) {
                $this->error("没有操作权限", C('USER_AUTH_GATEWAY'));
            }
        }
        //设置头信息
        $this->setHeader();
        //设置公共信息
        $this->setInfo();
    }

    public function setHeader() {
        //设置此页面的过期时间(用格林威治时间表示)
        header("Expires: Mon, 26 Jul 1970 05:00:00 GMT");
        //设置此页面的最后更新日期(用格林威治时间表示)为当天
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        //告诉客户端浏览器不使用缓存，HTTP 1.1 协议
        header("Cache-Control: no-cache, must-revalidate");
        //告诉客户端浏览器不使用缓存，兼容HTTP 1.0 协议
        header("Pragma: no-cache");
    }

    public function setInfo() {
        $sys['name'] = C('WEBNAME');
        $this->assign('sys', $sys);
        //用户信息
        $this->assign('userInfo', $this->userInfo);
        //显示菜单
        $this->showMenu();
    }

    /**
     * 后台权限验证
     * @return bool
     */
    protected function checkAdminAccess()
    {
        //检查是否登录
        if (!$this->adminUser->isLogin()) {
            redirect( C('USER_AUTH_GATEWAY') );
            return false;
        }
        if (empty($this->userInfo)) {
            $this->adminUser->logout();
            return false;
        }
        //超级管理员不受限制
        if ($this->adminUser->isAdministrator()) {
            return true;
        }
        //是否锁定
        if (!$this->userInfo['status']) {
            $this->adminUser->logout();
            $this->error('您的帐号已经被锁定！', C('USER_AUTH_GATEWAY'));
            return false;
        }
        //普通管理员权限检查
        $nodeModel = D("Node");
        $map = array(
            "module" => MODULE_NAME, "controller" => CONTROLLER_NAME, "action" => ACTION_NAME,
            'type'   => 1
        );
        $node = $nodeModel->field("nid")->where($map)->find();
        //当节点不存时，表示不需要验证, 这时直接允许操作
        if ( !$node ) {
            return true;
        } else {
            $map = array();
            $map['nid'] = $node['nid'];
            $map['rid'] = $this->userInfo['rid'];
            $auth = D('Access')->where($map)->find();
            return $auth ? true : false;
        }
    }

    //检测无需认证模块
    private function checkAuthModule($module = '', $allows = '') {
        $module = empty($module) ? $module : CONTROLLER_NAME;
        if($allows) {
            $mods = array();
            if(is_array($allows)) $mods = $allows;
            if(is_string($allows)) {
                foreach(explode(',', $allows) as $item) {
                    if(trim($item)!='') $mods[] = trim($item);
                }
            }
            if (in_array($module, $mods)) return true;
        }
        return false;
    }

    //获取菜单
    public function showMenu() {
        $prefix = C('DB_PREFIX');
        if(!$this->adminUser->isLogin())
            return false;
        //超级管理员返回所有菜单
        if ($this->adminUser->isAdministrator()) {
            $sysmenu = D('Node')->where("is_show=1")->order('list_order ASC')->select();
        } else {
            //管理员权限节点
            $sysmenu = M()->table("{$prefix}access a")
                ->join("{$prefix}node n ON n.nid=a.nid", "RIGHT")
                ->where("n.is_show=1 AND (n.type=2 OR a.rid={$this->adminUser->rid})")
                ->order('list_order ASC')
                ->select();
        }
        $sysmenu = \Common\Lib\Tool\Data::channelLevel($this->addNodeUrl($sysmenu), 0, '&nbsp;', 'nid');
        //分配菜单节点
        $this->assign('sysmenu', $sysmenu);
        //快捷菜单节点
        $quickMenu = M()
            ->table("{$prefix}panel m")
            ->join("{$prefix}node n ON m.nid=n.nid")
            ->where("uid={$this->adminUser->uid}")
            ->select();
        $this->assign('quickMenu', $this->addNodeUrl($quickMenu));
    }

    //获取菜单
    public function getMenu($menuid = NULL) {
        if(!$menuid) {
            $menuid = trim(I('menuid'));
        }
        $sysmenu = $this->get('sysmenu');
        $menu = array();
        if(!$menuid) $menuid = 'x';
        if(is_numeric($menuid)) {
            foreach($sysmenu as $k=>$item) {
                if($menuid == $item['nid']) {
                    $menu = $item['_data'];
                    break;
                }
            }
        }
        //常用菜单
        else {
            $menu = D('Panel')->getPanel($this->adminUser->uid);
            $menu = $this->addNodeUrl($menu);
        }
        $this->assign('menu', $menu);
        $this->assign('menuid', $menuid);
    }

    /**
     * 获得节点菜单
     * @param $node
     * @return mixed
     */
    protected function addNodeUrl($node)
    {
        if (empty($node)) {
            return array();
        }
        //设置链接
        foreach ($node as $n => $v) {
            if (empty($v['group'])) {
                $group = '';
            } else {
                $group = "g={$v['group']}&";
            }
            $param = empty($v['param']) ? '' : '&' . $v['param'];
            $node[$n]['url'] = __ROOT__
                . "/index.php?{$group}m={$v['module']}&c={$v['controller']}&a={$v['action']}" . $param;
        }
        return $node;
    }

    /**
     * 分页输出
     * @param integer $total 信息总数
     * @param integer $size 每页数量
     * @param integer $number 当前分页号（页码）
     * @param array $config 配置，会覆盖默认设置
     * @return object
     */
    protected function page($total, $size = 20, $number = 0, $config = array()) {
        $Page = page($total, $size, $number, $config);
        $Page->SetPager('default', '<span class="all">共有{recordcount}条信息</span>{first}{prev}{liststart}{list}{listend}{next}{last}');
        return $Page;
    }

    /**
     * 设置状态
     * @return string
     */
    public function setStatus($model = NULL, $statusField = NULL, $return = false)
    {
        $status = I('status',0,'intval');
        $id = I('id',0,'intval');
        $result = '';
        $model = $model ? $model : CONTROLLER_NAME;
        $model = is_object($model) ? $model : M($model);
        $pk = $model->getPk();
        $statusField = $statusField ? $statusField : 'status';
        $r = $model->where(array($pk=>$id))->setField($statusField, $status ? 1 : 0);
        if($r !== false) {
            $result = 'ok';
        }
        if($return) {
            return $result;
        }
        echo $result;
        exit();
    }

    //获取区域名称
    protected function getArea($id) {
        $area_name = '';
        if($id) {
            $r = D('Area')->where(array('id'=>$id))->find();
            if($r) {
                $area_name = $r['shortname'] ? $r['shortname'] : $r['areaname'];
                $area_name = str_replace(array('省', '市'), '', $area_name);
            }
        }
        return $area_name;
    }

}
